package com.ynny.chapter06.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ynny.chapter06.entity.User;
import com.ynny.chapter06.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //校验数据库用户名
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);

        User user = userMapper.selectOne(userQueryWrapper);

        //将user对象 绑定成  UserDetails对象

        UserDetails userDetails =
                org.springframework.security.core.userdetails.User
                        .withUsername(user.getUsername())
                        .password(user.getPassword())
                        .authorities("admin")
                        .build();

        return userDetails;
    }
}
